#include <bits/stdc++.h>
using namespace std;


class Solution {
public:
    typedef long long LL;

    int minWastedSpace(vector<int>& packages, vector<vector<int>>& boxes) {
        sort(packages.begin(), packages.end());

        int minid = -1;
        LL minwastedspace = LLONG_MAX, curwastedspace;;
        LL sum_packages = accumulate(packages.begin(), packages.end(), 0L); // !!!
        // cout << sum_packages << endl;
        for(int i = 0; i < boxes.size(); ++i){
            sort(boxes[i].begin(), boxes[i].end());
            if(boxes[i].back() < packages.back()) continue;

            LL sum_box = 0L;
            auto p_begin = packages.begin();
            for(int j = 0; j < boxes[i].size(); ++j){
                int box = boxes[i][j];
                auto p_cur = upper_bound(p_begin, packages.end(), box);
                sum_box += (p_cur - p_begin) * box;

                // cout << box << " " << (p_cur - p_begin) << " " << sum_box << endl;

                if(p_cur == boxes[i].end()) break;
                p_begin = p_cur;
            }
            curwastedspace = sum_box - sum_packages;
            cout << curwastedspace << endl;
            cout << endl;
            if(curwastedspace < minwastedspace){
                minid = i;
                minwastedspace = curwastedspace;
            }
        }

        if(minid == -1) return -1;
        return minwastedspace;
    }
};

int main(int argc, char const *argv[])
{
    Solution sol;
    
    vector<int> packages = {2,3,5}; // {3,5,8,10,11,12};
    vector<vector<int>> boxes = {
        {4,8},
        {2, 8},
        // {12},
        // {11,9},
        // {10,5,14}
    };
    
    int res = sol.minWastedSpace(packages, boxes);

    cout << res << endl;

    return 0;
}
